<?php
/**
 * User: hjd-yao
 * Date: 2019/1/11
 * Time: 15:58
 */

namespace App\Http\Controllers\Backend;


use App\Helpers\SelfResponse;
use App\Http\Controllers\BackendController;
use App\Models\System\AreaModel;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Storage;

class AreaController extends BackendController
{
    /**
     * @title 地区管理
     * @param int $parent_id
     * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View
     */
    public function showArea($parent_id=0)
    {
        $str = self::getParentsDistrict($parent_id);
        $list = AreaModel::where('parent_id',$parent_id)->get();
        return view('backend::area.index',[
            'page_title'=>'地区管理',
            'parent_id'=>$parent_id,
            'breadcrumbs'=>$str,
            'list'=>$list,
        ]);
    }

    /**
     * @title 添加地区
     * @param Request $request
     * @param int $parent_id
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse|\Illuminate\View\View
     */
    public function addArea(Request $request,$parent_id=0)
    {
        $page_title = '添加国家或地区';
        $level = 0;
        if($parent_id>0){
            $area_info = AreaModel::where('id',$parent_id)->first();
            if($area_info){
                $page_title = '添加'.$area_info->name.'下级行政区';
                $level = $area_info->level+1;
            }else{
                $parent_id = 0;
            }
        }

        if($request->isMethod('post')){
            $data = $request->only(['name','area_code','en_name','area_acronym','phone_code']);
            $data['parent_id'] = $parent_id;
            $data['level'] = $level;
            $data = AreaModel::init()->filterCode($parent_id,$data);
            $data = AreaModel::init()->convertName($data);
            $data['created_at'] = time();
            if(AreaModel::insert($data)){
                return SelfResponse::success('添加成功',['b_Area_showArea',['parent_id'=>$parent_id]]);
            }
            return SelfResponse::error('添加失败');
        }else{

            return view('backend::area.add_area',[
                'page_title'=>$page_title,
                'parent_id'=>$parent_id,
                'level'=>$level,
            ]);
        }
    }

    /**
     * @title 编辑地区
     * @param Request $request
     * @param $id
     * @return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse|\Illuminate\View\View
     */
    public function editArea(Request $request,$id)
    {
        $info = AreaModel::where('id',$id)->first();
        if($request->isMethod('post')){
            $data = $request->only(['name','area_code']);
            if(AreaModel::where('id',$id)->update($data)){
                return SelfResponse::success('更新成功',['b_Area_showArea',['parent_id'=>$info->parent_id]]);
            }
            return SelfResponse::error('更新失败');
        }else{
            return view('backend::area.edit_area',[
                'page_title'=>'编辑'.$info->name,
                'info'=>$info
            ]);
        }
    }

    /**
     * @title 删除地区
     * @param $id
     * @return SelfResponse|\Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
     */
    public function deleteArea($id)
    {
        $areaModel = new AreaModel();
        if(!$areaModel->delArea($id)){
            return SelfResponse::error($areaModel->getErrorMsg('删除失败'));
        }
        return SelfResponse::success('删除成功');
    }


    /**
     * @title 下载为json文件
     * @return mixed
     */
    public function exportAreaFile()
    {
        $data = $this->getWapCity();
        //dd($data);
        Storage::put('city.json',json_encode($data,JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT));
        return Storage::download('city.json');
    }

    /**
     * @title 请求地区信息
     * @return \Illuminate\Http\JsonResponse
     */
    public function getArea()
    {
        $data = $this->getAreaData();
        return response()->json($data);
    }

    private function getAreaData()
    {
        $list = AreaModel::where('parent_id','>',0)
            ->select(['id','name','parent_id'])->get();
        $data = [];
        foreach ($list as $key=> $item){
            $data[$key]['title'] = $item->name;
            $data[$key]['pid'] = $item->parent_id;
            if($item->parent_id == 1){
                $data[$key]['pid'] = $item->parent_id-1;
            }

            $data[$key]['id'] = $item->id;
        }
        unset($list);
        return $data;
    }

    private function getWapCity()
    {
        $list = AreaModel::where('parent_id','>',0)
            ->select(['id','name','parent_id'])->get();
        $data = [];
        foreach ($list as $key=> $item){
            $data[$key]['text'] = $item->name;
            $data[$key]['value'] = $item->id;
            $data[$key]['pid'] = $item->parent_id;
            if($item->parent_id == 1){
                $data[$key]['pid'] = $item->parent_id-1;
            }
        }
        unset($list);
        //dd($data);
        $tree = list_to_tree($data,true,'value','pid','children');
        return $tree;
    }

    private function getTreeData()
    {
        $info = AreaModel::all(['id','name','parent_id'])->toArray();
        $tree = list_to_tree($info,true,'id','parent_id','children');
        return $tree;
    }

    /**
     * @title 区域面包屑导航
     * @param $id
     * @param string $str
     * @return string
     */
    private function getParentsDistrict($id,&$str=''){
        $city = AreaModel::where(['id'=>$id])->first();
        if(!$city){
            return '全部地区';
        }
        if($str){
            $str = '<a href='.route('b_Area_showArea',['parent_id'=>$city['id']]).'>'.$city['name'].'</a>>'.$str;
        }else{
            $str = '<a href='.route('b_Area_showArea',['parent_id'=>$city['id']]).'>'.$city['name'].'</a>';
        }
        if($city['parent_id'] > 0){
            return self::getParentsDistrict($city['parent_id'],$str);
        }else{
            $str = '<a href='.route('b_Area_showArea',['parent_id'=>0]).'>全部地区</a>>'.$str;
        }
        return $str;
    }

}